# -*- coding: utf-8 -*-
import random
import scrapy
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from zc_core.util.http_util import retry_request
from scrapy.utils.project import get_project_settings
from norincogroup.rules import *
from zc_core.dao.sku_pool_dao import SkuPoolDao
from zc_core.dao.sku_dao import SkuDao
from zc_core.dao.batch_dao import BatchDao
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.done_filter import DoneFilter
from zc_core.spiders.base import BaseSpider


class FullSpider(BaseSpider):
    name = 'full_app'

    # web链接
    item_url_1 = 'https://ar.norincogroup-ebuy.com/exp/hangsource/buy/picksource/sourceInfo.do?gpls={}'
    # app链接
    item_url_2 = 'https://msapi.norincogroup-ebuy.com/supermarketweb/exp/hangsource/info?ssid=M11310&gpls={}'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(FullSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        # 创建批次记录
        BatchDao().create_batch(self.batch_no)
        # 避免重复采集
        self.done_filter = DoneFilter(self.batch_no)

    def start_requests(self):
        # pool_list_catalog = norincogroup_catalogDao().get_cat_list_from_pool()
        settings = get_project_settings()
        while_list = settings.get("CATALOG_WHITE_LIST")
        if while_list:
            pool_list = SkuDao().get_batch_sku_list(self.batch_no,
                                                    fields={'catalog1Name': 1, 'catalog1Id': 1, 'catalog2Name': 1,
                                                            'catalog2Id': 1, '_id': 1, 'offlineTime': 1},
                                                    query={"$or": while_list})
        else:
            pool_list = SkuDao().get_batch_sku_list(self.batch_no,
                                                    fields={'catalog1Name': 1, 'catalog1Id': 1, 'catalog2Name': 1,
                                                            'catalog2Id': 1, '_id': 1, 'offlineTime': 1}, query={})

        self.logger.info('全量：%s' % (len(pool_list)))
        # random.shuffle(pool_list)
        for sku in pool_list:
            sku_id = sku.get('_id')
            offline_time = sku.get('offlineTime', 0)
            settings = get_project_settings()
            if offline_time > settings.get('MAX_OFFLINE_TIME', 2):
                self.logger.info('忽略: [%s][%s]', sku_id, offline_time)
                continue
            # 避免重复采集
            if self.done_filter.contains(sku_id) and not settings.get('FORCE_RECOVER', False):
                self.logger.info('已采: [%s]', sku_id)
                continue
            # 采集商品
            yield Request(
                url=self.item_url_2.format(sku_id),
                callback=self.parse_item_data,
                errback=self.error_back,
                meta={
                    'reqType': 'item',
                    'batchNo': self.batch_no,
                    'skuId': sku_id,
                    # 'poolListCatalog':pool_list_catalog
                },
                priority=260,
            )

    # 处理ItemData
    def parse_item_data(self, response):
        data = parse_item_app_data(response)
        if data.__len__() == 1:
            self.logger.info('商品: [%s]已被丢弃（价格为0或者为空）' % data.get('skuId'))
        else:
            self.logger.info('商品: [%s]' % data.get('skuId'))
            yield data
